#!/usr/bin/env node
/**
 * Phase5 ChainValidator警告分级脚本
 *
 * 目的: 对chainvalidator的warnings进行分级,识别关键问题
 * 改进: critical警告触发Phase4修复流程,而非仅记录日志
 *
 * 执行时机: chainvalidator执行后
 * 质量门控: critical警告必须修复,medium/low可接受
 */

const fs = require('fs');
const path = require('path');

const PROJECT_ROOT = path.resolve(__dirname, '..');

/**
 * 警告严重级别定义
 */
const SEVERITY_RULES = {
  critical: [
    {
      pattern: /variant.*specific.*field.*未暴露/i,
      reason: 'variant-specific字段未在面板暴露,影响用户体验'
    },
    {
      pattern: /Figma.*panel.*代码.*无/i,
      reason: 'Figma设计有面板但代码未实现'
    },
    {
      pattern: /Edit.*引用.*文件.*不存在/i,
      reason: 'Edit配置引用的文件不存在'
    },
    {
      pattern: /\*Icon.*未.*暴露/i,
      reason: '图标字段未暴露,影响UI定制'
    },
    {
      pattern: /\*Img.*未.*暴露/i,
      reason: '图片字段未暴露,影响UI定制'
    },
    {
      pattern: /show\*.*未.*暴露/i,
      reason: '显示控制字段未暴露,影响功能配置'
    },
    {
      pattern: /has\*.*未.*暴露/i,
      reason: '特性开关字段未暴露,影响功能配置'
    }
  ],
  medium: [
    {
      pattern: /Field.*未在.*Edit.*暴露/i,
      reason: '字段在Fields定义但Edit未暴露,用户无法配置'
    },
    {
      pattern: /面板.*应复用/i,
      reason: '架构建议:面板应使用通用实现'
    }
  ],
  low: [
    {
      pattern: /Preview.*未使用/i,
      reason: 'Preview组件未使用某字段,可能冗余'
    },
    {
      pattern: /架构建议/i,
      reason: '架构优化建议'
    }
  ]
};

/**
 * 分类单个警告
 */
function classifyWarning(warning) {
  const message = warning.message || '';

  // 检查critical规则
  for (const rule of SEVERITY_RULES.critical) {
    if (rule.pattern.test(message)) {
      return {
        severity: 'critical',
        warning,
        rule: rule.reason
      };
    }
  }

  // 检查medium规则
  for (const rule of SEVERITY_RULES.medium) {
    if (rule.pattern.test(message)) {
      return {
        severity: 'medium',
        warning,
        rule: rule.reason
      };
    }
  }

  // 检查low规则
  for (const rule of SEVERITY_RULES.low) {
    if (rule.pattern.test(message)) {
      return {
        severity: 'low',
        warning,
        rule: rule.reason
      };
    }
  }

  // 默认medium
  return {
    severity: 'medium',
    warning,
    rule: '未分类警告'
  };
}

/**
 * 检查warning是否与Figma auxiliary相关
 */
function checkFigmaAuxiliaryContext(warning, componentCode) {
  const phase1Dir = path.join(PROJECT_ROOT, `${componentCode}/phase1`);

  const auxiliaryContentPath = path.join(phase1Dir, 'auxiliary/content/panel-structure.json');
  const auxiliaryStylePath = path.join(phase1Dir, 'auxiliary/style/panel-structure.json');

  if (!fs.existsSync(auxiliaryContentPath) && !fs.existsSync(auxiliaryStylePath)) {
    return { figmaHasPanel: false };
  }

  // 检查warning中提到的字段是否在auxiliary中定义
  const fieldName = warning.field;

  if (!fieldName) return { figmaHasPanel: false };

  let figmaHasPanel = false;

  [auxiliaryContentPath, auxiliaryStylePath].forEach(auxPath => {
    if (!fs.existsSync(auxPath)) return;

    const auxData = JSON.parse(fs.readFileSync(auxPath, 'utf-8'));
    const sections = auxData.sections || [];

    for (const section of sections) {
      const fields = section.fields || [];

      if (fields.some(f => (f.fieldKey || f.label).toLowerCase() === fieldName.toLowerCase())) {
        figmaHasPanel = true;
        break;
      }
    }
  });

  return { figmaHasPanel };
}

/**
 * 检查warning是否与variant相关
 */
function checkVariantContext(warning, componentCode) {
  const executionContext = path.join(PROJECT_ROOT, `${componentCode}/phase0/execution-context.json`);

  if (!fs.existsSync(executionContext)) {
    return { hasUIVariants: false };
  }

  const context = JSON.parse(fs.readFileSync(executionContext, 'utf-8'));
  const hasUIVariants = context?.figma?.hasUIVariants === true;

  if (!hasUIVariants) {
    return { hasUIVariants: false };
  }

  // 检查是否是variant-specific字段
  const previewPropsSchema = path.join(PROJECT_ROOT, `${componentCode}/phase2/preview-props-schema.json`);

  if (!fs.existsSync(previewPropsSchema)) {
    return { hasUIVariants: true, isVariantSpecific: false };
  }

  const schema = JSON.parse(fs.readFileSync(previewPropsSchema, 'utf-8'));
  const variantHandling = schema.variantHandling;

  if (!variantHandling) {
    return { hasUIVariants: true, isVariantSpecific: false };
  }

  const fieldName = warning.field;
  let isVariantSpecific = false;

  // 检查字段是否在某个variant的propsSubset中
  for (const variant of variantHandling.variants || []) {
    if ((variant.propsSubset || []).includes(fieldName)) {
      isVariantSpecific = true;
      break;
    }
  }

  return {
    hasUIVariants: true,
    isVariantSpecific,
    controlField: variantHandling.controlField
  };
}

/**
 * 主分类函数
 */
async function classifyWarnings(componentCode) {
  console.log(`\n=== ChainValidator警告分级: ${componentCode} ===\n`);

  // Step 1: 读取validation-results.json
  const validationPath = path.join(
    PROJECT_ROOT,
    `${componentCode}/phase5/${componentCode}-validation-results.json`
  );

  if (!fs.existsSync(validationPath)) {
    console.error('错误: 未找到validation-results.json');
    console.error(`路径: ${validationPath}`);
    return { error: 'validation-results.json不存在' };
  }

  const validation = JSON.parse(fs.readFileSync(validationPath, 'utf-8'));
  const warnings = validation.results?.chainValidator?.warnings || [];

  console.log(`发现 ${warnings.length} 个警告\n`);

  // Step 2: 分类警告
  const classification = {
    timestamp: new Date().toISOString(),
    componentCode,
    totalWarnings: warnings.length,
    byCategory: {
      critical: [],
      medium: [],
      low: []
    },
    summary: {
      critical: 0,
      medium: 0,
      low: 0
    },
    recommendation: null
  };

  for (const warning of warnings) {
    const classified = classifyWarning(warning);

    // 增强context信息
    const figmaContext = checkFigmaAuxiliaryContext(warning, componentCode);
    const variantContext = checkVariantContext(warning, componentCode);

    const enhancedWarning = {
      ...classified,
      context: {
        ...figmaContext,
        ...variantContext
      }
    };

    // 重新评估severity(基于context)
    if (figmaContext.figmaHasPanel && enhancedWarning.severity !== 'critical') {
      enhancedWarning.severity = 'critical';
      enhancedWarning.rule = 'Figma设计有面板但代码未实现';
    }

    if (variantContext.isVariantSpecific && enhancedWarning.severity !== 'critical') {
      enhancedWarning.severity = 'critical';
      enhancedWarning.rule = 'variant-specific字段未暴露';
    }

    classification.byCategory[enhancedWarning.severity].push(enhancedWarning);
    classification.summary[enhancedWarning.severity]++;
  }

  // Step 3: 输出结果
  console.log('=== 分级结果 ===\n');
  console.log(`🔴 Critical: ${classification.summary.critical}`);
  console.log(`🟡 Medium:   ${classification.summary.medium}`);
  console.log(`🟢 Low:      ${classification.summary.low}\n`);

  if (classification.summary.critical > 0) {
    console.log('Critical警告详情:\n');

    classification.byCategory.critical.forEach((w, idx) => {
      console.log(`${idx + 1}. [${w.warning.layer}] ${w.warning.field}`);
      console.log(`   消息: ${w.warning.message}`);
      console.log(`   原因: ${w.rule}`);

      if (w.context.figmaHasPanel) {
        console.log(`   ⚠️  Figma auxiliary中存在此字段的面板设计`);
      }

      if (w.context.isVariantSpecific) {
        console.log(`   ⚠️  variant-specific字段,控制字段: ${w.context.controlField}`);
      }

      console.log();
    });
  }

  // Step 4: 生成建议
  if (classification.summary.critical > 0) {
    classification.recommendation = {
      action: 'trigger_phase4_remediation',
      reason: `存在 ${classification.summary.critical} 个critical警告,需要修复`,
      targetPhase: 'Phase4',
      affectedFields: classification.byCategory.critical.map(w => w.warning.field)
    };

    console.log('🚨 建议操作: 触发Phase4修复流程\n');
  } else {
    classification.recommendation = {
      action: 'accept_warnings',
      reason: '所有警告为medium/low级别,可接受',
      targetPhase: 'continue'
    };

    console.log('✅ 所有警告为非关键级别,可继续\n');
  }

  // 保存分类报告
  const outputPath = path.join(PROJECT_ROOT, `${componentCode}/phase5/warning-classification.json`);
  fs.writeFileSync(outputPath, JSON.stringify(classification, null, 2), 'utf-8');
  console.log(`分类报告已保存: ${path.relative(PROJECT_ROOT, outputPath)}`);

  return classification;
}

// CLI执行
if (require.main === module) {
  const componentCode = process.argv[2];

  if (!componentCode) {
    console.error('用法: node scripts/phase5-warning-classifier.js <ComponentCode>');
    process.exit(1);
  }

  classifyWarnings(componentCode)
    .then(classification => {
      const hasCritical = classification.summary?.critical > 0;
      process.exit(hasCritical ? 1 : 0);
    })
    .catch(err => {
      console.error('执行失败:', err);
      process.exit(1);
    });
}

module.exports = { classifyWarnings };
